import { create } from 'zustand';
import { cartItem } from '../models/CartModel';

interface CartState {
  bears: number;
  increase: (by: number) => void;
  //   购物车数据列表
  cartList: cartItem[];
  // 修改数据
  cartChange: (item: cartItem) => void;
  //   全选反选
  cartSelectAll: (status: boolean) => void;
  //   加入购物车
  cartAdd: (item: cartItem) => void;
  // 移除购物车
  cartDel: (id: string) => void;
}

export const useCartStore = create<CartState>()(set => ({
  bears: 0,
  increase: by => set(state => ({ bears: state.bears + by })),
  cartList: [],
  cartChange: item =>
    set(state => {
      const index = state.cartList.findIndex(i => i.id === item.id);
      if (index !== -1) {
        state.cartList[index] = item;
      }
      return {
        cartList: state.cartList,
      };
    }),
  cartSelectAll: status => {
    set(state => {
      state.cartList.forEach(item => {
        item.status = status;
      });
      return {
        cartList: state.cartList,
      };
    });
  },
  cartAdd: item => {
    set(state => {
      const index = state.cartList.findIndex(i => i.id === item.id);
      if (index !== -1) {
        state.cartList[index].num += 1;
      } else {
        state.cartList.push(item);
      }
      return {
        cartList: state.cartList,
      };
    });
  },
  cartDel: id => {
    set(state => {
      const index = state.cartList.findIndex(item => item.id === id);
      if (index !== -1) {
        state.cartList.splice(index, 1);
      }
      return {
        cartList: state.cartList,
      };
    });
  },
}));
